var topiccode=paramMap.topiccode;
var dbname=paramMap.dbname;
var result = paramMap.result;
var objtype=paramMap.objtype||'TAB';
var curTeamCode=paramMap.teamcode||'T0001';
var shopCartItems={};
var baseSql="select dbname,cnname from metadb_list where 1=1 and dbname='"+dbname+"'";
var baseStore = new AI.JsonStore({
        sql:baseSql,
        pageSize:-1,
        key:"DBNAME"
});
var cycleSql="select rowcode,rowname from metaedimdef where dimcode ='DIM_"+objtype+"_CYCLE'";
var cycleStore = new AI.JsonStore({
        sql:cycleSql,
        pageSize:-1,
        key:"ROWCODE"
});
var topicSql="select rulecode,rulename,parentcode from metadb_struct WHERE DBNAME = '"+dbname+"'";
var topicStore = new AI.JsonStore({
        sql:topicSql,
        pageSize:-1,
        key:"RULECODE"
});
//var hiSql="select * from table_his";
//var hiStore = new AI.JsonStore({
//        sql:hiSql,
//        pageSize:-1,
//        key:"XMLID"
//});

function buildShopCart(){
	var eleFlyElement = document.querySelector("#flyItem"), eleShopCart = document.querySelector("#shopCart");
	var numberItem = 0;
	  var myParabola = funParabola(eleFlyElement, eleShopCart, {
	  speed: 400, //抛物线速度
	  curvature: 0.0008, //控制抛物线弧度
	  complete: function() {
	    eleFlyElement.style.visibility = "hidden";
	    eleShopCart.querySelector("span").innerHTML = numberItem;
//	    var selObjTpl=' <li class="list-group-item"> <div class="clear">{OBJNAME} </div> <span class="pull-right"> a href="#"><i class="fa fa-times icon-muted fa-fw"></i></a> </span></li>';
//	    var objname=itemStore.curRecord.get(metaInfo.keyfield);
//	    var html=selObjTpl.replace("{OBJNAME}",objname);
//	    $("#shopCartList").append(html);
	 
	  }
	});
	if (eleFlyElement && eleShopCart) {
	  //[].slice.call(document.getElementsByClassName("icon-basket")).forEach(function(button) {		
	  [].slice.call(document.getElementsByName("addMyFav")).forEach(function(button) {
	    button.addEventListener("click", function(event) {
	    	console.log($(this).parent().parent().parent().parent().attr("id")+","+$(this).parent().parent().parent().parent().attr("title"));
	    	var objid=$(this).parent().parent().parent().parent().attr("id");
	    	var objname=$(this).parent().parent().parent().parent().attr("title");
	    	if(!shopCartItems[objid]){
	    		shopCartItems[objid]=objname;
	    		numberItem++;
	    	}
	    	else{
	    		return false;
	    	}
	      // 滚动大小
	      var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft || 0,
	          scrollTop = document.documentElement.scrollTop || document.body.scrollTop || 0;
	      eleFlyElement.style.left = event.clientX + scrollLeft + "px";
	      eleFlyElement.style.top = event.clientY + scrollTop + "px";
	      eleFlyElement.style.visibility = "visible";
	      
	      // 需要重定位
	      myParabola.position().move();     
	    });
	  });
	};
	 
	$("#shopCart").popover({
		  content:function(){
			  var content='<section class="panel panel-info" style="width:270px"><ul class="list-group" id="shopCartList">';
			  var selObjTpl=' <li class="list-group-item" id="{objid}"> {OBJNAME}</li>';
			  
			  for(var key in shopCartItems){
				  var objname=shopCartItems[key];
				  var Itemhtml=selObjTpl.replace("{OBJNAME}",objname);
				  Itemhtml=Itemhtml.replace("{objid}",key);
				  content+=Itemhtml;
			  }
			  content+='</ul>';
			  content+='<div class="panel-footer">'
			  content+='<button type="button" class="btn btn-default btn-xs">清空</button>';
			  content+='<button type="button" class="btn btn-default btn-xs">申请</button>';
			  content+='<button type="button" class="btn btn-default btn-xs">分析</button>';
				 
			  content+='</section>';
			  return content;
		  },
	      html:'true',
	      placement:'top',
	      title:'选择的对象',show:true,trigger: 'manual'})
	           .on("mouseenter", function () {
	                    var _this = this;
	                    $(this).popover("show");
	                    $(this).siblings(".popover").on("mouseleave", function () {
	                        $(_this).popover('hide');
	                    });
	                }).on("mouseleave", function () {
	                    var _this = this;
	                    setTimeout(function () {
	                        if (!$(".popover:hover").length) {
	                            $(_this).popover("hide")
	                        }
	                    }, 100);
	                });
}

var exportData = function() {
  ai.addTabSheet('objChoose', '导出对象选择',  "/"+ contextPath+"/ftl/me/metaframe/ai.meta.exportchoose?OBJTYPE=" + objtype + "&TEAMCODE=" + curTeamCode, true);
}

 ///申请状态查询，申请
$(document).ready(function() {//*通过初始化配置和事件，进行界面个性化定制，
  var curDBInfo = ai.getStoreData("select distinct a.alias dbtype from metadbcfg a where a.dbname = 'METADB'");
  //var curDBName = ai.getStoreData("select distinct dbname from tablefile where topiccode like '"+topiccode+"%'");
  if(curDBInfo.length>0&&curDBInfo[0].DBTYPE=='oracle'){
    tabSQL = "select XMLID,'TAB' OBJTYPE,DATANAME,DATACNNAME,DBNAME,TOPICCODE,CYCLETYPE,ROWNUM_VAL,FIELDNUM,STATE_DATE,STATE,REMARK from tablefile where state='PUBLISHED' and dbname = '"+dbname+"'"+(topiccode?" and topiccode in (select rulecode from metadb_struct a  connect by prior a.rulecode = a.parentcode start with a.rulecode='{topiccode}')":"");
  }else{
    tabSQL = "select XMLID,'TAB' OBJTYPE,DATANAME,DATACNNAME,DBNAME,TOPICCODE,CYCLETYPE,ROWNUM_VAL,FIELDNUM,STATE_DATE,STATE,REMARK from tablefile where dbname = '"+dbname+"'"+(topiccode?" and topiccode like '{topiccode}%'":"");
  }
  
  
  config={
    TAB:{
      title:'数据',
      sql:tabSQL,
      tpl:'<div class="dacptiles panel panel-success " id="{{XMLID}}" title="{{DATANAME}}" objtype="TAB"><header class="panel-heading"><img class="flag" id="{{XMLID}}_flag" style="margin-left: -30px;margin-top: -6px;margin-bottom: -20px;width: 26px;" src="" style="display:none"/><span class="part-one">{{CYCLECNTYPE}}</span>      <span class="part-two">{{DBCNNAME}}</span><ul class="nav nav-pills pull-right"></ul></header><div class="row"><div class="col-md-12" style="padding-left:30px;text-align:left;"><h5><b>{{DATANAME}}<b></b></b></h5><b><b><small><b>{{DATACNNAME}}</b></small></b></b></div></div><div class="row fieldinfo"></div><div class="panel-footer bg-light lter text-center" style="margin-top:10px"><div class="row pull-out"><div class="col-xs-4"><div class="padder-v"><span class="m-b-xs h5 block">{{FIELDCNNUM}}</span><small class="text-muted">字段数</small></div></div><div class="col-xs-4 dk"><div class="padder-v"><small class="m-b-xs h5 block">{{ROWNUM_CNVAL}}</small><small class="text-muted">记录数</small></div></div><div class="col-xs-4"><div class="padder-v"><small class="m-b-xs h5 block">{{STATE_DATE}}</small><small class="text-muted">状态时间</small></div></div></div></div><div class="tabDetal" id="{{XMLID}}_detail" style="z-index: 99; position: absolute; margin-left: 20px; margin-top:-140px;background:#eee;height:auto;width:auto;display:none"></div></div>',
      columns:[
        {header: "数据库",dataIndex:'DBNAME', headerAlign: "center", dataAlign: "center", width: "120" ,sortable:true,
        render:function(rowData,colVal){
          if(baseStore&&baseStore.getCount()>0){
            var dim = _.find(baseStore.root,function(obj){
              if(obj.DBNAME == colVal) return obj;
            });
            colVal = dim&&dim.CNNAME?dim.CNNAME:colVal;
          }
          return colVal;
        }},
        {header: "名称", dataIndex: "DATANAME", headerAlign: "center",width: "180",sortable:true,maxLength:30},
        {header: "中文名", dataIndex: "DATACNNAME", headerAlign: "center", dataAlign: "center", width: "250",sortable:true,maxLength:30 },
        {header: "主题",dataIndex:'TOPICCODE', headerAlign: "center", dataAlign: "center", width: "120" ,sortable:true,
        render:function(rowData,colVal){
        	if(!colVal||colVal=='null') return '未知';
        	var topicNames = [];
        	function getTopicName(topicCode){
        		var dim = _.find(topicStore.root,function(obj){
            		if(obj.RULECODE == topicCode) return obj;
          		});
        		topicNames.push(dim&&dim.RULENAME?dim.RULENAME:topicCode);
          		if(!_.isUndefined(dim)&&dim.PARENTCODE) getTopicName(dim.PARENTCODE);
        	}
        	if(topicStore&&topicStore.getCount()>0){
        		getTopicName(colVal);
          	}
        	var result = "";
        	for(i=topicNames.length-1;i>=0;i--){
        		result += '/' + topicNames[i];
        	}
        	return result||colVal;
        }},
        {header: "周期",dataIndex:'CYCLETYPE', headerAlign: "center", dataAlign: "center", width: "80" ,sortable:true,
        render:function(rowData,colVal){
          if(cycleStore&&cycleStore.getCount()>0){
            var dim = _.find(cycleStore.root,function(obj){
              if(obj.ROWCODE == colVal) return obj;
            });
            colVal = dim&&dim.ROWNAME?dim.ROWNAME:colVal;
          }
          return colVal;
        }},
        {header: "状态",dataIndex:'STATE', headerAlign: "center", dataAlign: "center", width: "80" ,sortable:true,dimStore:new AI.JsonStore({sql:"SELECT rowcode,rowname FROM metaedimdef WHERE dimcode = 'DIM_STATE'",pageSize:-1})
        ,render:function(rowData,colVal){
          if(this.dimStore&&this.dimStore.getCount()>0){
            var dim = _.find(this.dimStore.root,function(obj){
              if(obj.ROWCODE == colVal) return obj;
            });
            colVal = dim&&dim.ROWNAME?dim.ROWNAME:colVal;
          }
          return colVal;
        }},
        {header: "备注",dataIndex:'REMARK', headerAlign: "center", dataAlign: "center", width: "250" ,sortable:true,maxLength:50}
      ],
      toolbarconfig:[
         //chenliang10 20160929 1、escape下划线 2、添加表名前缀过滤
         {type:'text',fieldLabel:'表名',width:50,name:'name',where:"(upper(DATANAME) like upper('%{name}%') escape '_' or upper(DATACNNAME) like upper('%{name}%') escape '_')"}
        ,{type:'text',fieldLabel:'字段名',width:100,name:'colname',where:"(dataname in (select dataname from column_val where upper(colname) like upper('%{colname}%') escape '_' or upper(colcnname) like upper('%{colname}%') escape '_'))"}
        ,{type:'combox',fieldLabel:'数据库',width:210,name:'dataname',storesql:'select dbname,cnname from metadb_list',where:"dbname='{dataname}'"}
        ,{type:'combox',fieldLabel:'状态',width:170,name:'state',storesql:"select rowcode,rowname from metaedimdef where dimcode = 'DIM_STATE'",where:" state = '{state}' ", value: "PUBLISHED"}
        ,{type:'text',fieldLabel:'表名前缀过滤',width:100,name:'name_nomatch',where:"(upper(DATANAME) not like upper('{name_nomatch}%') escape '_' and upper(DATACNNAME) not like upper('{name_nomatch}%') escape '_')"}
        ,{type:'button',fieldLabel:'查询',id:'queryid',fn:queryData,width:120}
        // ,{type:'button',fieldLabel:'导出',id:'exportTab',fn:exportColumn,width:120}
        ,{type:'button',fieldLabel:'导出',id:'exportTab',fn:exportData,width:120}
      ]
    },
    DATATRANS:{
      title:'数据分发',
      sql:"SELECT XMLID,INTERCODE, INTERNAME, TRANSTYPE, SOURCE_DB, SOURCE_TAB,EXPTYPE,TARGET_DB, TARGET_TAB FROM data_trans_config ",
      tpl:'<div class="dacptiles panel panel-default " id="{{XMLID}}" title="{{INTERNAME}}" objtype="DATATRANS"><div class="row">     <b>{{SOURCE_DB}}->{{TARGET_DB}}</b>     <h5>{{SOURCE_TAB}}</h5><small>{{TARGET_TAB}}</small>    </div><div class="row fieldinfo"></div><div class="panel-footer bg-light lter text-center" style="margin-top:10px"><div class="row pull-out"><div class="col-xs-4"><div class="padder-v"><span class="m-b-xs h5 block">日</span><small class="text-muted">周期</small></div></div><div class="col-xs-4 dk"><div class="padder-v"><small class="m-b-xs h5 block">{{TRANSTYPE}}</small><small class="text-muted">类型</small></div></div><div class="col-xs-4"><a href="#" actid="cancelApplyData" class="metaaction" style="color:red"><div class="padder-v "><span class="m-b-xs h5 block">{{EXPTYPE}}</span><small class="text-muted ">导入类型</small></div></a></div></div></div></div>',
      columns:[
               {header: "编号", dataIndex: "INTERCODE", headerAlign: "center",width: "80",sortable:true,maxLength:30},
               {header: "类型", dataIndex: "TRANSTYPE", headerAlign: "center",width: "80",sortable:true,maxLength:30},
               {header: "源库",dataIndex:'SOURCE_DB', headerAlign: "center", dataAlign: "center", width: "80" ,sortable:true,
               render:function(rowData,colVal){
                 if(baseStore&&baseStore.getCount()>0){
                   var dim = _.find(baseStore.root,function(obj){
                     if(obj.DBNAME == colVal) return obj;
                   });
                   colVal = dim&&dim.CNNAME?dim.CNNAME:colVal;
                 }
                 return colVal;
               }},
               {header: "源表", dataIndex: "SOURCE_TAB", headerAlign: "center",width: "280",sortable:true,maxLength:30},
               {header: "目标库", dataIndex: "TARGET_DB", headerAlign: "center", dataAlign: "center", width: "80",sortable:true,maxLength:30,
            	   render:function(rowData,colVal){
                       if(baseStore&&baseStore.getCount()>0){
                         var dim = _.find(baseStore.root,function(obj){
                           if(obj.DBNAME == colVal) return obj;
                         });
                         colVal = dim&&dim.CNNAME?dim.CNNAME:colVal;
                       }
                       return colVal;
            	   }
               },
               {header: "目标表",dataIndex:'TARGET_TAB', headerAlign: "center", dataAlign: "center", width: "280" ,sortable:true},
               {header: "周期",dataIndex:'CYCLETYPE', headerAlign: "center", dataAlign: "center", width: "80" ,sortable:true,
               render:function(rowData,colVal){
                 if(cycleStore&&cycleStore.getCount()>0){
                   var dim = _.find(cycleStore.root,function(obj){
                     if(obj.ROWCODE == colVal) return obj;
                   });
                   colVal = dim&&dim.ROWNAME?dim.ROWNAME:colVal;
                 }
                 return colVal;
               }},
               {header: "模板编号",dataIndex:'STATE', headerAlign: "center", dataAlign: "center", width: "80"},
               {header: "备注",dataIndex:'REMARK', headerAlign: "center", dataAlign: "center", width: "150" ,sortable:true,maxLength:50}
             ],
             toolbarconfig:[
               {type:'text',fieldLabel:'表名',width:120,name:'name',where:"(upper(DATANAME) like upper('%{name}%') or upper(DATACNNAME) like upper('%{name}%'))"}
               ,{type:'text',fieldLabel:'字段名',width:120,name:'colname',where:"(dataname in (select dataname from column_val where upper(colname) like upper('%{colname}%') or upper(colcnname) like upper('%{colname}%')))"}
               ,{type:'combox',fieldLabel:'数据库',width:210,name:'dataname',storesql:'select dbname,cnname from metadb_list',where:"dbname='{dataname}'"}
               ,{type:'combox',fieldLabel:'状态',width:210,name:'state',storesql:"select rowcode,rowname from metaedimdef where dimcode = 'DIM_STATE'",where:" state = '{state}' "}
               ,{type:'button',fieldLabel:'查询',id:'queryid',actionId:'queryMetaObj',width:120}
               // ,{type:'button',fieldLabel:'导出',id:'exportTab',fn:exportColumn,width:120}
               ,{type:'button',fieldLabel:'导出',id:'exportTab',fn:exportData,width:120}
             ]
    },
    OPENAPI:{
      title:'数据开放',
      sql:"SELECT XMLID,'OPENAPI' OBJTYPE,a.API_ID, API_CODE, API_LABEL, API_DESCR,CATEGORY,RESPONSE_TYPE,VERSION_NO,DBNAME,STATE,REQUEST_URL,CREATE_USER,USE_NUMBER ROWNUM_VAL,USE_TIMES FIELDNUM,CHARGE_TIMES FROM dacp_dataex_api a",
      tpl:'<div class="dacptiles panel panel-default " id="{{API_ID}}" title="{{API_CODE}}" objtype="OPENAPI"><div class="row"><div class="col-md-4">      <span class="glyphicon glyphicon-bullhorn" style="margin-top:1px;margin-left:10px;  font-size:48px "></span>      <code>{{CATEGORY}}</code></div><div class="col-md-8"><div style="margin-left:-60px;"><h5>{{API_LABEL}}</h5><small>{{API_LABEL}}</small><code style="right: 15px;top: 0px;position: absolute;">{{STATE}}</code></div></div></div><div class="row">    <div class="col-md-12">     <small> {{REQUEST_URL}}</small></div></div><div class="row fieldinfo"></div><div class="panel-footer bg-light lter text-center" style="margin-top:10px"><div class="row pull-out"><div class="col-xs-4"><a href="#" actid="configColumn" class="metaaction" style="color:red"><div class="padder-v "><span class="m-b-xs h5 block">{{ROWNUM_CNVAL}}</span><small class="text-muted ">使用人数</small></div></a></div><div class="col-xs-4 dk"><a href="#" actid="rejectApplyData" class="metaaction" style="color:red"><div class="padder-v "><span class="m-b-xs h5 block">{{FIELDCNNUM}}</span><small class="text-muted ">使用次数</small></div></a></div><div class="col-xs-4"><a href="#" actid="agreeApplyData" class="metaaction" style="color:red"><div class="padder-v "><span class="m-b-xs h5 block"><span class="glyphicon glyphicon-thumbs-up"></span></span><small class="text-muted ">评价</small></div></a></div></div></div></div>',
      columns:[
        {header: "API编码",dataIndex:'API_CODE', headerAlign: "center", dataAlign: "center", width: "120" ,sortable:true},
        {header: "API名称", dataIndex: "API_LABEL", headerAlign: "center",width: "180",sortable:true,maxLength:30},
        {header: "API地址", dataIndex: "REQUEST_URL", headerAlign: "center", dataAlign: "center", width: "200",sortable:true,maxLength:30 },
        {header: "创建人",dataIndex:'CREATE_USER', headerAlign: "center", dataAlign: "center", width: "120" ,sortable:true},
        {header: "状态",dataIndex:'STATE', headerAlign: "center", dataAlign: "center", width: "80" ,sortable:true},
        {header: "使用人数",dataIndex:'USE_NUMBER', headerAlign: "center", dataAlign: "center", width: "80" ,sortable:true},
        {header: "使用次数",dataIndex:'USE_TIMES', headerAlign: "center", dataAlign: "center", width: "80" ,sortable:true},
        {header: "计费次数",dataIndex:'CHARGE_TIMES', headerAlign: "center", dataAlign: "center", width: "80" ,sortable:true},
        {header: "备注",dataIndex:'API_DESCR', headerAlign: "center", dataAlign: "center", width: "200" ,sortable:true,maxLength:50}
      ],
      toolbarconfig:[
        {type:'text',fieldLabel:'API名称',width:120,name:'name',where:"(upper(API_CODE) like upper('%{name}%') or upper(API_LABEL) like upper('%{name}%'))"}
        ,{type:'text',fieldLabel:'API地址',width:120,name:'colname',where:"upper(REQUEST_URL) like upper('%{colname}%')"}
        ,{type:'button',fieldLabel:'查询',id:'queryid',actionId:'queryMetaObj',width:120}
      ]
    },
    ZB:{
      title:'指标库',
      sql:"select * from DAG_META_ZB  ",
      tpl:'<div class="dacptiles panel panel-success " id="{{XMLID}}" title="{{ZB_CODE}}" objtype="ZB"><header class="panel-heading"><span class="part-one">荐</span>      <span class="part-two">{{DBCNNAME}}</span><ul class="nav nav-pills pull-right">           </ul></header><div class="row"><div class="col-md-12" style="padding-left:30px;text-align:left;"><h5><b>{{ZB_CODE}}<b></b></b></h5><b><b><small><b>{{ZB_NAME}}</b></small></b></b></div></div><div class="row fieldinfo"></div><div class="panel-footer bg-light lter text-center" style="margin-top:10px"><div class="row pull-out"><div class="col-xs-4"><div class="padder-v"><span class="m-b-xs h5 block">{{OP_TIME}}</span><small class="text-muted">数据时间</small></div></div><div class="col-xs-4 dk"><div class="padder-v"><small class="m-b-xs h5 block">{{CUR_VALUE}}</small><small class="text-muted">当前值</small></div></div><div class="col-xs-4"><div class="padder-v"><small class="m-b-xs h5 block">{{ALERM_VALUE}}</small><small class="text-muted">告警值</small></div></div></div></div></div>'
    }
  }
  var meta=new  AI.Meta({});
  var metaModel=meta.getMetaModel(objtype);
   
  var metaInfo = metaModel.metaInfo;
 
  var querysql=config[objtype].sql.replace("{topiccode}",topiccode);
  itemStore = new AI.JsonStore({
                sql: querysql,
                pageSize:20,
                key:"XMLID"
      });
    var columns=[];
    for(var i=0;i<5;i++){
      var attrItem = metaModel.attrArray[i];
      columns.push({header: attrItem.attrcnname||attrItem.attrname,dataIndex:attrItem.attrname, headerAlign: "center", dataAlign: "center", width: "150" ,sortable:true});
    };
    
    function queryData(){
    	var grid=listView.gridUx;
    	var where = " where 1=1 ";
		for(var i=0;i<grid.toolbars.length;i++){
		    var itemUx = grid.toolbars[i];
		    if(itemUx&&itemUx.getValue()&&itemUx.config.where){
		    	var val=itemUx.getValue();
		    	if((itemUx.config.name=='colname' || itemUx.config.name=='name' || itemUx.config.name=='name_nomatch') && val.indexOf('_')!=-1){
		    		val=val.replace(/_/g,'__');
		    	}
		    	
		    	where += " and "+itemUx.config.where.replace(eval('/{'+itemUx.config.name+'}/g'),val);
		    }
		}
		grid.store.sql = "select * from ("+grid.store.oldsql+" ) a "+where;
		grid.control.find('.cur-page-text').val(1);
		grid.control.trigger('filtered.fu.repeater');
    }

    function changeToCn(store,type1,type2,code){
      if(store.getCount()>0){
          if(code!=null){
           code=code.trim();
           for(var i=0;i<store.getCount();i++){
                if(store.getAt(i).get(type1).trim()==code){
                  return store.getAt(i).get(type2);
                }else{
                  continue;
                }
            }
          }else{
            code='无'
            return code;
          }
      }else{
        return code==null?'无':code;
      }
      return !code?'无':code;         
    }
    var listView = new AI.MetaList({containerId:'frame-right-main',
      store:itemStore,
      objtype:objtype,
      title:config[objtype].title,
      bodyHtml:'<div class="repeater-canvas col-md-12" style="padding-left:1px;padding-right:1px;height:100%;overflow:auto"></div> ',
      columns:config[objtype].columns,
      show:true,
      card:{
        tpl:config[objtype].tpl
      },
      preParaDataStore:function(store){
        for(var i=0;i<itemStore.getCount();i++){
          var r=itemStore.getAt(i);
          r.set('ROWINDEX',i);
          r.set('DBCNNAME',changeToCn(baseStore,'DBNAME','CNNAME',r.get('DBNAME')));
          var cycle=changeToCn(cycleStore,'ROWCODE','ROWNAME',r.get('CYCLETYPE'));
          // if(cycle==null){
          //   cycle='无';
          // }
          r.set('CYCLECNTYPE',cycle);
          r.set('TOPICCNNAME',changeToCn(topicStore,'RULECODE','RULENAME',r.get('TOPICNAME')));
          if(r.get("FIELDNUM")==null){
            r.set('FIELDCNNUM','--');
          }else{
            r.set('FIELDCNNUM',r.get("FIELDNUM"));
          }
          if(r.get("ROWNUM_VAL")==null){
            r.set('ROWNUM_CNVAL','--');
          }else{
            r.set('ROWNUM_CNVAL',r.get("ROWNUM_VAL"));
          }
        }
      },
      click:function(e){
        var $this = $(e.currentTarget);
         
        $this.toggleClass('large');
        
        if($this.hasClass('large')){
           if($('.detail',$this).length==0){
            $('.fieldinfo',$this).append(getColumnInfo($this.attr("id"))).addClass("detail");
            
            
           };
            
           $(".detail",$this).show();
           $(".detail a").click(function(e){
               e.stopPropagation();
               var $this = $(e.currentTarget);
               $this.parents('.dacptiles').trigger('dblclick');
           });
       
           $(".panel-heading",$this).addClass("header-panel");
           $(".dacptiles.panel",$this).addClass("md-col");
           $(".part-two",$this).addClass("color-chg");
           $(".part-two",$this).addClass("class-chg");
           $(".dacptiles .nav>li>a",$this).addClass("color-chg");
           $(".nav>li>a>img",$this).addClass("icon-class");
           $(".text-muted",$this).addClass("color-chg");
           $(".nav i",$this).css("color","#EFF5FB");
        }
        else{
          
           $this.children().show();
           $(".detail",$this).hide();
           $(".panel-heading",$this).removeClass("header-panel");
           $(".dacptiles.panel",$this).removeClass("md-col");
           $(".part-two",$this).removeClass("color-chg");
           $(".part-two",$this).removeClass("class-chg");
           $(".dacptiles .nav>li>a",$this).removeClass("color-chg");
           $(".nav>li>a>img",$this).removeClass("icon-class");
           $(".text-muted",$this).removeClass("color-chg");
           $(".nav i",$this).css("color","#5CAEA5");
        };
        if(objtype=='TAB') $container.isotope('reLayout');
        return false;
      },
      contextMenu:function(){
        
      },
      toolbarconfig:config[objtype].toolbarconfig||[],
      // fieldInfoArray:result.fieldInfoArray||[],
      loadtype:'dataindex'
      });

    var config_store = listView.config.store;
    listView.config.store.oldsql = listView.config.store.oldsql.replace("state='PUBLISHED' and ","");
    listView.options.store.oldsql = listView.options.store.oldsql.replace("state='PUBLISHED' and ","");
    
    //如果是模型数据目录，就调整状态字段宽度以便不换行
    if(objtype=='TAB')
    	  $("#state").css("width","160px");
   
      listView.on("dblclick",function(objid){
                 
      });
      listView.on("loaded",function(objid){
        renderCardAction();
        if(objtype=='TAB')loadCardIsotope();
      });

      var renderCardAction = function(){
        var objid = $(".dacptiles.panel.panel-success").attr("id");
        var objInfo=meta.getMetaObjBaseInfo(objtype,objid,'record');
        if(!objInfo){
          console.log('Error,通过id:'+objid+'未获取到对象!');
          return;
        }
        var dockplace="rightmenu";
        var actionItems=meta.getMetaObjActionItems(objtype,dockplace);
        //$("#card-choose a span").append('<div class="row"></div>');
        var i=0;
        $(".dacptiles ul").empty();
        for(key in actionItems){
          i++;
          if(actionItems[key].getright){
                actionItems[key].disabled = false;
                var result = actionItems[key].getright(objInfo,_UserInfo,meta.getMetaInfo(objtype),'dataindex');
                if(result == 'hide') {i--;continue;};
                if(result == 'disabled'){
                  actionItems[key].disabled = true;
                }
             }
              var href = actionItems[key].url;
              var icon = actionItems[key].icon;
              var actName = actionItems[key].name;  
             if(i>4){
              break;
             }
             
            $(".dacptiles ul").prepend('<li><a href="#" name="'+key+'" data-toggle="tooltip" data-placement="bottom" title="'+actName+'"><i class="'+icon+'"></i></a></li>');
              // if(i%3==0){
              //   $("#card-choose a span").append('<div class="row"></div>'); 
              // }
            
          }
          $(".dacptiles ul li a").click(function(e){
            var $this = $(e.currentTarget);
            e.stopPropagation();
            objid = $this.parent().parent().parent().parent().attr("id");
            objInfo=meta.getMetaObjBaseInfo(objtype,objid,'record');
            listView.metaAction({actionkey:$(this).attr('name')},objInfo);
          });
      }

      var loadCardIsotope = function(){
        $container = $('#myRepeater .repeater-thumbnail-cont');
        $container.isotope({
          itemSelector : '.thumbnail',
          masonry : {
            columnWidth : 80
          },
           itemPositionDataEnabled: true,
          masonryHorizontal : {
            rowHeight: 240
          },
          cellsByRow : {
            columnWidth : 240,
            rowHeight : 240
          },
          cellsByColumn : {
            columnWidth : 140,
            rowHeight : 120
          }
        });
      }
 
        renderCardAction();
        if(objtype=='TAB') loadCardIsotope();
        
   var   checkAct=function(actid,record){
      actfunArray=['applyData','cancelApplyData','configColumn','rejectApplyData','agreeApplyData','dataSendApply'];
      if(actfunArray.indexOf(actid)==-1) return false;
      return true;
    };
     $(".metaaction").click(function(event){
       var actId=$(this).attr("actid");
       var applyXmlId = $(this).parent().parent().parent().parent().attr("id");
       var objname=$(this).parent().parent().parent().parent().attr("title");
       console.log(itemStore.curRecord.data);
       if(!checkAct(actId,record)) {alert('不允许您当前的操作');return;};
       
       if(actId=="applyData") {
        if(applyData(applyXmlId,objname,curTeamCode)==false) return false;
         $(this).html('审批中..<p><a href="#">撤回</a>');
         alert('已经提交申请,涉及到敏感表,需要管理员审批');
         $(this).parent().parent().parent().parent().parent().remove();
       }else if(actId=="cancelApplyData") {
        var str = window.prompt("拒绝原因","权限不符合要求") 
         if(cancelApplyData(applyXmlId,curTeamCode,str)){
          $(this).html('拒绝申请<p>'+str+'<a href="#">撤回</a>');
        };
       }else if(actId=="configColumn") {
         configColumn(applyXmlId,curTeamCode,itemStore);
          
       }else if(actId=="rejectApplyData") {
        var rejectRemark = window.prompt("拒绝原因","权限不符合要求") 
         if(cancelApplyData(applyXmlId,curTeamCode,rejectRemark)){
          $(this).html('拒绝申请<p>'+str+'<a href="#">撤回</a>');
        };
       }else if(actId=="agreeApplyData") {
        agreeApplyData(applyXmlId,curTeamCode);
         $(this).parent().parent().parent().parent().parent().remove();
         
       }else if(actId=="dataSendApply"){
         dataSendApply();
      }
       if(objtype=='TAB') $container.isotope('reLayout');
       event.stopPropagation();
       return false;
    });
  function getColumnInfo(xmlid){
     var coldata = ai.getStoreData("select colname,colcnname from column_val where xmlid='"+xmlid+"' order by col_seq");
     var html="";
     for(var i=0;i<coldata.length;i++){
      html+='<div class="col-xs-6"><small pull-left"> <i class="fa fa-clock-o"></i> '+coldata[i].COLNAME.toLowerCase()+","+coldata[i].COLCNNAME+'</small></div> ';
      if(i>=18){
        html+='<div class="col-xs-6"><a href="#" id="getMoreDetail"><span class="label label-primary pull-left">查看更多>></span></a></div>';
        break;
      }
    };
    return html; 
  }; 
   
  
  //bind 购物车
  buildShopCart();
  
  //给模型贴上变更和新建标识    
 var putFlag=function(){
   var _flag=0;
   for(var i=0;i<itemStore.getCount();i++){
      var xmlid= itemStore.getAt(i).get('XMLID');
      if(itemStore.getAt(i).get('STATE')=="NEW"){
	    var id=xmlid+"_flag";
	    $("#"+id).attr("src","${mvcPath}/dacp-res/images/new.png");
		$("#"+id).show();
		continue;
	  }
	  _flag=0;
      
	  for(var j=0;j<hiStore.getCount();j++){
	    var _xmlid=hiStore.getAt(j).get('XMLID');
		if(xmlid!=_xmlid){		   
		   _flag++;
		}
	  }
	  if(_flag!=hiStore.getCount()){
	    var id=xmlid+"_flag";
	    $("#"+id).attr("src","${mvcPath}/dacp-res/images/update.png");
		$("#"+id).show();
	  }
  }
 }
 //得到模型变更的内容
  var getModContent=function(xmlid){
     var modcontent="";
	 var modcontent1="";
     var colStore=new AI.JsonStore({
                sql:"select * from column_val where xmlid='"+xmlid+"'",
                pageSize:20,
                key:"XMLID"
      });
	  var colhiStore=new AI.JsonStore({
                sql:"select * from column_his where xmlid='"+xmlid+"'",
                pageSize:20,
                key:"XMLID"
      });
	  var _flag1=0;
	  var _flag2=0;
	  var _flag3=0;
	  for(var i=0;i<colStore.getCount();i++){
	     _flag1=0;
	     var colname= colStore.getAt(i).get('COLNAME');
	     for(var j=0;j<colhiStore.getCount();j++){
		   _flag3=0;
		   modcontent1="";
	       var _colname=colhiStore.getAt(j).get('COLNAME');
		   if(colname!=_colname){		   
		    _flag1++;
		   }else{
		     if(colStore.getAt(i).get('COLCNNAME')){
			    if(colStore.getAt(i).get('COLCNNAME')!=colhiStore.getAt(j).get('COLCNNAME')){
				   modcontent1+="中文名称改成"+colStore.getAt(i).get('COLCNNAME')+"，";
				   _flag3++;
				}
			 }else{
			    if(colhiStore.getAt(j).get('COLCNNAME')){
			       modcontent1+="中文名称被删除，";
				   _flag3++;
				}
			 }
             if(colStore.getAt(i).get('DATATYPE')!=colhiStore.getAt(j).get('DATATYPE')){
			    modcontent1+="类型改成"+colStore.getAt(i).get('DATATYPE')+"，";
				_flag3++;
			 }
             if(colStore.getAt(i).get('LENGTH')){
			    if(colStore.getAt(i).get('LENGTH')!=colhiStore.getAt(j).get('LENGTH')){
				   modcontent1+="长度改成"+colStore.getAt(i).get('LENGTH')+"，";
				   _flag3++;
				}
			 }else{
			    if(colhiStore.getAt(j).get('LENGTH')){
				   modcontent1+="长度被删除，";
				   _flag3++;
				}			   
			 }
			 if(colStore.getAt(i).get('PRECISION_VAL')){
			    if(colStore.getAt(i).get('PRECISION_VAL')!=colhiStore.getAt(j).get('PRECISION_VAL')){
				   modcontent1+="精确度改成"+colStore.getAt(i).get('PRECISION_VAL')+"，";
				   _flag3++;
				}
			 }else{
			    if(colhiStore.getAt(j).get('PRECISION_VAL')){
				   modcontent1+="精确度被删除，";
				   _flag3++;
				}			   
			 }
			 if(colStore.getAt(i).get('KEY_SEQ')){
			    if(colStore.getAt(i).get('KEY_SEQ')!=colhiStore.getAt(j).get('KEY_SEQ')){
				   modcontent1+="主键属性被设置，";
				   _flag3++;
				}
			 }else{
			    if(colhiStore.getAt(j).get('KEY_SEQ')){
				   modcontent1+="主键属性被撤销，";
				   _flag3++;
				}			   
			 }
             if(colStore.getAt(i).get('ISNULLABLE')!=colhiStore.getAt(j).get('ISNULLABLE')){
			    if(colStore.getAt(i).get('ISNULLABLE')=='N'){
				   modcontent1+="是否为空属性设为否，";
				   _flag3++;
				}else{
				   modcontent1+="是否为空属性设为是，";
				   _flag3++;
				}
			    
			 }
             if(colStore.getAt(i).get('DEFAULT_VAL')){
			    if(colStore.getAt(i).get('DEFAULT_VAL')!=colhiStore.getAt(j).get('DEFAULT_VAL')){
				   modcontent1+="默认值改成"+colStore.getAt(i).get('DEFAULT_VAL')+"，";
				   _flag3++;
				}
			 }else{
			    if(colhiStore.getAt(j).get('DEFAULT_VAL')){
				   modcontent1+="默认值被删除，";
				   _flag3++;
				}			   
			 }
			 if(colStore.getAt(i).get('REMARK')){
			    if(colStore.getAt(i).get('REMARK')!=colhiStore.getAt(j).get('REMARK')){
				   modcontent1+="备注改成"+colStore.getAt(i).get('REMARK')+"，";
				   _flag3++;
				}
			 }else{
			    if(colhiStore.getAt(j).get('DEFAULT_VAL')){
				   modcontent1+="备注被删除，";
				   _flag3++;
				}			   
			 }
		   }
		   if(_flag3!=0){
			    modcontent1="字段"+colhiStore.getAt(j).get('COLNAME')+"的"+modcontent1;
				//var end=modcontent1.lastIndexOf("，");
				modcontent1=modcontent1.substring(0,modcontent1.length-1)+"；";
		   }	
		   modcontent+=modcontent1;
	     }
	    if(_flag1==colhiStore.getCount()){
	       modcontent+="增加了字段"+colStore.getAt(i).get('COLNAME')+"；";
		}
		
	  }
	  for(var i=0;i<colhiStore.getCount();i++){
	     _flag2=0;
	     var colname= colhiStore.getAt(i).get('COLNAME');
	     for(var j=0;j<colStore.getCount();j++){
	       var _colname=colStore.getAt(j).get('COLNAME');
		   if(colname!=_colname){		   
		    _flag2++;
			}
		 }
		 if(_flag2==colStore.getCount()){
		   modcontent+="字段"+colhiStore.getAt(i).get('COLNAME')+"被删除；";
		 }
	  }
	  return modcontent;
  }
  //得到模型变更或新建标识弹出框的内容
  var getTabDetail=function(str,xmlid,imgsrc){
	  var flagStore=new AI.JsonStore({
                sql:"select * from tablefile where xmlid='"+xmlid+"'",
                pageSize:20,
                key:"XMLID"
      });
	  
	  var r=flagStore.getAt(0);
	  var _creater=r.get('CREATER');
	  var _credate=r.get('EFF_DATE');
	  var _modifier=r.get('CURDUTYER');
	  var _moddate=r.get('STATE_DATE');
	  var _modcontent=str;
	  var tabDetal="";
	  if(imgsrc=="/new.png"){
	    var tabDetal='<span  style="height:60px;cursor:default">创建者：'+_creater+'</span><br><br>'
 				    +'<span  style="height:60px;cursor:default">创建时间：'+_credate+'</span>';
	  }
	  if(imgsrc=="/update.png"){
	    var tabDetal='<span  style="height:60px;cursor:default">修改人：'+_modifier+'</span><br>'
 				    +'<span  style="height:60px;cursor:default">修改时间：'+_moddate+'</span><br>'
				    +'<span  style="height:60px;cursor:default">修改内容：'+_modcontent+'</span>';
	  }   
	  $(tabDetal).appendTo('#'+xmlid+'_detail');
  }
  //给鼠标绑定进入和移出标识的事件
 var bundmouseFunc=function(){
  $(".flag").mouseenter(function(){
      var end=this.id.indexOf('_');
      var xmlid=this.id.substring(0,end);
	  var src=this.src;
	  var start=src.lastIndexOf("/");
	  var imgsrc=src.substring(start);
	  if(imgsrc=="/update.png"){
	    var _modcontent=getModContent(xmlid);
	  }  
	  getTabDetail(_modcontent,xmlid,imgsrc);
	  var id=xmlid+"_detail";
	  $("#"+id).show();
  });
  $(".flag").mouseleave(function(){
        var end=this.id.indexOf('_');
        var xmlid=this.id.substring(0,end);
	    var id=xmlid+"_detail";
		$("#"+id).empty(); 
		$("#"+id).hide();
  });
 }
 /*
 putFlag();
 bundmouseFunc();
 $("#queryid").on('click',function(){
    putFlag();
	bundmouseFunc();
 });
 $('#queryid').click();//初始化列表时触发一次查询事件
  */
});
 
 
